<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
    <input type="text">
    <button id="btnSend">发送请求</button>
    <button id="btnCancel">取消请求</button>


    <script>
        const oIpt = document.querySelector("input")
        const oBtnSend = document.querySelector("#btnSend")
        const oBtnCancel = document.querySelector("#btnCancel")

        //声明一个取消的对象（是一个构造函数）
        const CancelToken = axios.CancelToken;

        //在全局中声明一个取消的函数，赋值为null
        let cancel = null




        //创建一个axios的实例
        const myAxios = axios.create({
            baseURL: "/",
            timeout: 10000,
            headers: {}
        })

        //给axios的实例添加请求拦截
        myAxios.interceptors.request.use(config => {
            const token = "afdoashf,ijgisjga,sadgaiygwdi"
            config.headers.token = token
            console.log(token);

            return config
        })

        //给发送请求添加点击事件
        oBtnSend.onclick = async function () {
            const ipiData = oIpt.value
            try {
                const re = await myAxios.get("/user-delay", {
                    params: {
                        userId: ipiData
                    },
                    //在配置对象中配置一个CancelToken的配置项，值是实例化CancelToken对象
                    cancelToken: new CancelToken(c => {
                        // console.log(c);
                        cancel = c
                    })
                })
            } catch (e) {
                console.log(e);
            }
        }

        oBtnCancel.onclick = function () {
            // 调用取消函数
            cancel()
        }
    </script>
</body>

</html>